package com.ponhu.ea2.stockcenter.provider.service.biz.stockinit.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouse;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouseRelation;
import com.ponhu.ea2.stockcenter.provider.mapper.StockInventoryRealMapper;
import com.ponhu.ea2.stockcenter.provider.service.biz.stockinit.GWallStockDataService;
import com.ponhu.ea2.stockcenter.provider.service.biz.stockinit.StockDataInitService;
import com.ponhu.ea2.stockcenter.provider.service.entity.StockWarehouseRelationService;
import com.ponhu.ea2.stockcenter.provider.service.entity.StockWarehouseService;
import com.ponhu.ea2.stockcenter.provider.support.vo.InventoryVO;
import com.ponhu.ea2.wmscenter.model.bms.dto.PhWarehouseDto;
import com.ponhu.ea2.wmscenter.model.bms.vo.GoodsStockInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wang
 * @date 2021/11/6 3:32 下午
 */
@Slf4j
@Service
public class StockDataInitServiceImpl implements StockDataInitService {

    @Autowired
    private StockInventoryRealMapper stockInventoryRealMapper;

    @Autowired
    private GWallStockDataService gWallStockDataService;

    @Autowired
    private StockWarehouseRelationService stockWarehouseRelationService;

    @Autowired
    private StockWarehouseService stockWarehouseService;

    /**
     * 初始化库存中心数据
     */
    @Override
    public void initStockData() {
        int pageSize = 100;

        //1.从"任务中心"分页获取仓库货品库存数据，写入仓库货品库存表
        List<StockWarehouse> warehouseCodeList = stockWarehouseService.list();

        //货品数量
        Integer count = stockInventoryRealMapper.calcInventoryCount();
        if (count == null || count < 1) {
            log.error("数据库货品数据为空，请先初始化货品数据至实物库存表");
            return;
        }
        log.info("====> 货品数据总数量为:{}", count);
        int pages = count / pageSize + 1;

        log.info("====> 货品数据分页长度为:{} ====> 总页数为: {}", pageSize, pages);

        for (StockWarehouse warehouse : warehouseCodeList) {
            if (!startInitWarehouseStock(pageSize, pages, warehouse)) return;
        }
    }

    private boolean startInitWarehouseStock(int pageSize, int pages, StockWarehouse warehouse) {
        log.info("开始处理 ====> 当前仓库 {}:{}", warehouse.getWarehouseName(), warehouse.getWarehouseCode());

        Page<InventoryVO> page2 = new Page<>();
        page2.setSize(pageSize);

        for (int i = 1; i <= pages; i++) {
            page2.setCurrent(i);
            IPage<InventoryVO> inventoryPage = stockInventoryRealMapper.selectInventoryPage(page2);

            List<InventoryVO> inventoryList = inventoryPage.getRecords();

            List<String> inventoryCodeList = inventoryList.stream().map(InventoryVO::getInventoryCode).collect(Collectors.toList());

            List<GoodsStockInfoVo> gWallStockData = null;
            try {
                gWallStockData = gWallStockDataService.getGWallStockDataNew(warehouse.getWarehouseCode(), inventoryCodeList);

                if (gWallStockData == null) {
                    log.info("==============> 从wms获取仓库库存数据为null，继续下一次执行 =============> ");
                    continue;
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("==============> 从wms获取仓库数据异常，初始化中止：{} =============> ", e.getMessage());
                return false;
            }

            List<StockWarehouseRelation> relations = stockWarehouseRelationService.getStockWarehouseRelations(inventoryCodeList, warehouse.getWarehouseCode());

            //更新的结果集
            List<StockWarehouseRelation> stockWarehouseRelationList = new ArrayList<>();
            for (GoodsStockInfoVo g : gWallStockData) {
                if (g.getQty() != null && g.getQty().intValue() != 0) {
                    //根据wms要sku，查询货品，获取货品ID等信息
                    InventoryVO inventoryVO = inventoryList.stream().filter(
                            f -> f.getInventoryCode().equals(g.getSku())).findFirst().orElse(null);

                    if (inventoryVO == null) {
                        continue;
                    }

                    //查看数据库是否有当前仓库的货品
                    StockWarehouseRelation relation = relations.stream().filter(r -> r.getInventoryCode().equals(g.getSku()) &&
                            r.getWarehouseCode().equals(warehouse.getWarehouseCode())).findFirst().orElse(null);

                    if (relation != null && relation.getRealStockNum().intValue() != g.getQty()) {
                        //更新库存
                        relation.setRealStockNum(g.getQty())
                                .setAvailableStockNum(g.getQty())
                                .setCreateTime(null);
                        stockWarehouseRelationList.add(relation);
                    }

                    if (relation == null) {
                        //插入库存
                        relation = new StockWarehouseRelation();
                        relation.setInventoryCode(g.getSku())
                                .setRealStockNum(g.getQty())
                                .setAvailableStockNum(g.getQty())
                                .setLockedStockNum(0)
                                .setWarehouseCode(warehouse.getWarehouseCode())
                                .setInventoryId(inventoryVO.getInventoryId());

                        stockWarehouseRelationList.add(relation);
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(stockWarehouseRelationList)) {
                //将数据更新至数据库
                stockWarehouseRelationService.saveOrUpdateBatch(stockWarehouseRelationList);
            }
            log.info("====> 仓库{} ====> 初始化货品数量为: {}", warehouse.getWarehouseName(), stockWarehouseRelationList.size());
        }
        return true;
    }
}
